#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <cstring>
#include <sstream>
using namespace std;
#include <sstream>

template <typename T>
std::string to_string(T value)
{
    std::ostringstream os;
    os << value;
    return os.str();
}
int main()
{
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    if (n < 0)
    {
        perror("pipe error");
        exit(1);
    }
    pid_t pid = fork();
    if (pid < 0)
    {
        perror("fork error");
        exit(1);
    }
    else if (pid == 0)
    {
        close(pipefd[0]);
        // int cnt = 0;
        // while (true)
        // {
        //     char a = 'b';
        //     write(pipefd[1], &a, 1);
        //     cout << cnt++ << "\n" << endl;
        // }
        string str = "hello father ,  我是子进程";
        string self = to_string(getpid());
        int cnt = 0;
        string message = str + "," + self + "," + to_string(cnt) + "\n";
        while (true)
        {
            char c = 'A' + cnt;
            write(pipefd[1], &c, 1);
            sleep(1);
            cnt++;
            // write(pipefd[1], message.c_str(), message.size());
            // message = str + "," + self + "," + to_string(++cnt) + "\n";
            // sleep(1);
        }
        close(pipefd[1]);
        cout << "写端关闭" << endl;
        sleep(5);
        exit(0);
    }
    else
    {
        close(pipefd[1]);
        while (true)
        {
            /* code */
            char c;
            ssize_t n = read(pipefd[0], &c, 1);
            if (n > 0)
            {
                cout << "child send message: " << c << endl;
            }
            else if (n == 0)
            {
                cout << "return value is 0, pipe has been closed" << endl;
                // break;
                sleep(1);
            }
            else
            {
                perror("read error");
                exit(1);
            }
            break;
        }
        close(pipefd[0]);
        cout << "读端关闭" << endl;
        int status = 0;
        pid_t rid = waitpid(pid, &status, 0);
        if(rid > 0)
        {
            int exitcode = (status >> 8) & 0xFF;
            int exitsig = status & 0x7F;
            cout << "child process " << rid << " exit code: " << exitcode << " signal: " << exitsig << endl;
        }
        // char buffer[1024] = {0};
        // while (true)
        // {
        //     // ssize_t s = read(pipefd[0], buffer, sizeof(buffer) - 1);
        //     // if (s > 0)
        //     // {
        //     //     buffer[s] = 0;
        //     //     cout << "father get message from child: " << buffer << endl;
        //     // }
        // }
    }
    return 0;
}